﻿using JNPF.Basics.Logic;
using JNPF.Basics.Models;
using JNPF.Basics.Models.System.Dtos.Message;
using JNPF.Basics.Models.System.Dtos.MessageNoticeOutput;
using JNPF.Utils;
using JNPF.Utils.Controller;
using Microsoft.AspNetCore.Mvc;
using System.Linq;
using System.Threading.Tasks;

namespace JNPF.Basics.Controller
{
    /// <summary>
    /// 系统消息
    /// 版 本：V3.0.0
    /// 版 权：引迈信息技术有限公司（https://www.jnpfsoft.com）
    /// 作 者：JNPF开发平台组
    /// 日 期：2017-12-27
    /// </summary>
    [Route("api/System/[controller]")]
    public class MessageController : BaseApiController
    {
        private MessageBll messageBll = new MessageBll();
        private UserBll userBll = new UserBll();

        #region GET
        /// <summary>
        /// 列表（通知公告）
        /// </summary>
        /// <param name="requestParam">请求参数</param>
        /// <returns></returns>
        [HttpGet("Notice")]
        public async Task<ResponseResult> GetNoticeList([FromQuery] PageInput requestParam)
        {
            var data = await messageBll.GetNoticeList(requestParam);
            var dataList = data.list.Select(x => new MessageNoticeOutput()
            {
                id = x.Id,
                lastModifyTime = x.LastModifyTime,
                enabledMark = x.EnabledMark,
                title = x.Title,
                creatorUser = userBll.GetUserName(x.LastModifyUserId)
            }).ToList();
            var output = new PageResult<MessageNoticeOutput>
            {
                list = dataList,
                pagination = data.pagination
            };
            return Success(output);
        }

        /// <summary>
        /// 列表（通知公告/系统消息/私信消息）
        /// </summary>
        /// <param name="requestParam">请求参数</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<ResponseResult> GetMessageList([FromQuery] MessageListInput requestParam)
        {
            if (requestParam.type != 0)
            {
                var data = await messageBll.GetMessageList(requestParam, requestParam.type.ToString());
                var output = new PageResult<MessageListOutput>
                {
                    list = data.list.Select(x => new MessageListOutput()
                    {
                        creatorUser = userBll.GetUserName(x.CreatorUserId),
                        id = x.Id,
                        isRead = x.IsRead,
                        lastModifyTime = x.LastModifyTime,
                        title = x.Title,
                        type = x.Type
                    }).ToList(),
                    pagination = data.pagination
                };
                return Success(output);
            }
            else
            {
                var data = await messageBll.GetMessageList(requestParam);
                var output = new PageResult<MessageListOutput>
                {
                    list = data.list.Select(x => new MessageListOutput()
                    {
                        creatorUser = userBll.GetUserName(x.CreatorUserId),
                        id = x.Id,
                        isRead = x.IsRead,
                        lastModifyTime = x.LastModifyTime,
                        title = x.Title,
                        type = x.Type
                    }).ToList(),
                    pagination = data.pagination

                };
                return Success(output);
            }
        }

        /// <summary>
        /// 信息
        /// </summary>
        /// <param name="id">主键值</param>
        /// <returns></returns>
        [HttpGet("{id}")]
        public async Task<ResponseResult> GetInfo(string id)
        {
            var data = (await messageBll.GetInfo(id)).MapTo<MessageInfoOutput>();
            return Success(data);
        }

        /// <summary>
        /// 读取消息
        /// </summary>
        /// <param name="id">主键值</param>
        /// <returns></returns>
        [HttpGet("ReadInfo/{id}")]
        public async Task<ResponseResult> ReadInfo(string id)
        {
            var data = (await messageBll.GetInfo(id)).MapTo<MessageReadInfoOutput>();
            data.creatorUser = userBll.GetUserName(data.creatorUser);
            if (data != null)
            {
                await messageBll.MessageRead(id);
            }
            return Success(data);
        }
        #endregion

        #region POST
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id">主键值</param>
        /// <returns></returns>
        [HttpDelete("{id}")]
        public async Task<ResponseResult> Delete(string id)
        {
            var entity = await messageBll.GetInfo(id);
            if (entity != null)
            {
                await messageBll.Delete(entity);
            }
            return Success("删除成功");
        }

        /// <summary>
        /// 新建
        /// </summary>
        /// <param name="input">实体对象</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ResponseResult> Create([FromBody] MessageCrInput input)
        {
            var entity = input.MapTo<MessageEntity>();
            await messageBll.Create(entity);
            return Success("新建成功");
        }

        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="id">主键值</param>
        /// <param name="input">实体对象</param>
        /// <returns></returns>
        [HttpPut("{id}")]
        public async Task<ResponseResult> Update(string id, [FromBody] MessageUpInput input)
        {
            var entity = await messageBll.GetInfo(id);
            entity.Title = input.title;
            entity.BodyText = input.bodyText;
            await messageBll.Update(id, entity);
            return Success("更新成功");
        }

        /// <summary>
        /// 发布公告
        /// </summary>
        /// <param name="id">主键值</param>
        /// <returns></returns>
        [HttpPut("{id}/Actions/Release")]
        public async Task<ResponseResult> Release(string id)
        {
            var entity = await messageBll.GetInfo(id);
            if (entity != null)
            {
                var userList = await userBll.GetList();
                entity.ToUserIds = string.Join(",", userList.Select(m => m.Id).ToList());
                await messageBll.SentNotice(entity.ToUserIds.Split(',').ToList(), entity);
            }
            return Success("发送成功");
        }

        /// <summary>
        /// 全部已读
        /// </summary>
        /// <returns></returns>
        [HttpPost("Actions/ReadAll")]
        public async Task<ResponseResult> AllRead()
        {
            await messageBll.MessageRead();
            return Success("已读成功");
        }

        /// <summary>
        /// 删除记录
        /// </summary>
        /// <param name="postParam">请求参数</param>
        /// <returns></returns>
        [HttpDelete("Record")]
        public async Task<ResponseResult> DeleteRecord([FromBody] dynamic postParam)
        {
            string[] ids = postParam.ids.ToString().Split(',');
            await messageBll.DeleteRecord(ids.ToList());
            return Success("删除成功");
        }
        #endregion
    }
}
